package cn.xiaobai.j2exe.controller;

import cn.hutool.core.swing.DesktopUtil;
import cn.xiaobai.j2exe.AbstractApplication;
import cn.xiaobai.j2exe.CallBack;
import cn.xiaobai.j2exe.handler.JSConnector;
import cn.xiaobai.j2exe.utils.DialogUtils;
import cn.xiaobai.j2exe.utils.SourceUtils;
import javafx.concurrent.Worker;
import javafx.fxml.FXML;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import netscape.javascript.JSObject;

import java.awt.*;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * 使用教程控制器, 显示软件使用教程
 *
 * @Author yangdaji
 * @Date 2023/12/30
 * @PackageName cn.xiaobai.j2exe.controller
 * @ClassName UsageViewController
 */
public class UsageViewController extends AbstractApplication implements CallBack<Object> {


    @FXML
    private WebView web_view;

    private JSObject javascriptConnector;

    /**
     * js 通信对象
     */
    private JSConnector javaConnector;

    @Override
    public void call(Object param) {
        // 控制回调
//        System.out.println("接收: " + param);

        // 触发系统浏览器打开
        Desktop dsktop = DesktopUtil.getDsktop();
        try {
            URL url = new URL(param.toString());
            dsktop.browse(url.toURI());
        } catch (Exception e) {
            System.err.println("link fail: " + e.fillInStackTrace());
            DialogUtils.popUp("异常", e.getMessage());
        }


    }

    @Override
    protected void refresh() {

    }

    @Override
    protected void updateInitDir() {

    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        addListener(this);
        regisJs();
    }

    /**
     * 注册 js 交互
     */
    private void regisJs() {
        WebEngine engine = web_view.getEngine();
        URL html = SourceUtils.getHtml("index.html");
        String externalForm = html != null ? html.toExternalForm() : "";

        engine.getLoadWorker().stateProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if (Worker.State.SUCCEEDED == newValue) {
                        javascriptConnector = (JSObject) engine.executeScript("window");
                        javaConnector = new JSConnector(javascriptConnector, this);

                        // web 引擎中注册 javaConnector 对象用于js 调用
                        javascriptConnector.setMember("javaConnector", javaConnector);
                    }
                });
        engine.load(externalForm);
    }

}
